package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysAeration;
import com.ruoyi.system.domain.SysUserAeration;
import com.ruoyi.system.service.ISysAerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 增氧机信息
 *
 * @author xiongdong
 */
@RestController
@RequestMapping("/system/aeration")
public class SysAerationController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysAerationService aerationService;

    @PreAuthorize("@ss.hasPermi('system:aeration:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAeration sysAeration)
    {
        startPage();
        List<SysAeration> list = aerationService.selectSysAerationList(sysAeration);
        return getDataTable(list);
    }

    @Log(title = "增氧机管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:aeration:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAeration sysAeration)
    {
        List<SysAeration> list = aerationService.selectSysAerationList(sysAeration);
        ExcelUtil<SysAeration> util = new ExcelUtil<SysAeration>(SysAeration.class);
        util.exportExcel(response, list, "增氧机数据");
    }

    /**
     * 根据增氧机编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:query')")
    @GetMapping(value = "/{aerId}")
    public AjaxResult getInfo(@PathVariable Long aerId)
    {
        aerationService.checkAerationDataScope(aerId);
        return success(aerationService.selectAerationById(aerId));
    }

    /**
     * 新增增氧机
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:add')")
    @Log(title = "增氧机管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysAeration sysAeration)
    {
        if (UserConstants.NOT_UNIQUE.equals(aerationService.checkAerationNameUnique(sysAeration)))
        {
            return error("新增增氧机'" + sysAeration.getAerName() + "'失败，增氧机名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(aerationService.checkAerationKeyUnique(sysAeration)))
        {
            return error("新增增氧机'" + sysAeration.getAerName() + "'失败，增氧机权限已存在");
        }
        sysAeration.setCreateBy(getUsername());
        return toAjax(aerationService.insertAeration(sysAeration));

    }

    /**
     * 修改保存增氧机
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:edit')")
    @Log(title = "增氧机管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysAeration sysAeration)
    {
        aerationService.checkAerationAllowed(sysAeration);
        aerationService.checkAerationDataScope(sysAeration.getAerId());
        if (UserConstants.NOT_UNIQUE.equals(aerationService.checkAerationNameUnique(sysAeration)))
        {
            return error("修改增氧机'" + sysAeration.getAerName() + "'失败，增氧机名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(aerationService.checkAerationKeyUnique(sysAeration)))
        {
            return error("修改增氧机'" + sysAeration.getAerName() + "'失败，增氧机权限已存在");
        }
        sysAeration.setUpdateBy(getUsername());

        if (aerationService.updateAeration(sysAeration) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改增氧机'" + sysAeration.getAerName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:edit')")
    @Log(title = "增氧机管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysAeration sysAeration)
    {
        aerationService.checkAerationAllowed(sysAeration);
        aerationService.checkAerationDataScope(sysAeration.getAerId());
        return toAjax(aerationService.authDataScope(sysAeration));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:edit')")
    @Log(title = "增氧机管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysAeration sysAeration)
    {
        aerationService.checkAerationAllowed(sysAeration);
        aerationService.checkAerationDataScope(sysAeration.getAerId());
        sysAeration.setUpdateBy(getUsername());
        return toAjax(aerationService.updateAerationStatus(sysAeration));
    }

    /**
     * 删除增氧机
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:remove')")
    @Log(title = "增氧机管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{aerIds}")
    public AjaxResult remove(@PathVariable Long[] aerIds)
    {
        return toAjax(aerationService.deleteAerationByIds(aerIds));
    }

    /**
     * 获取增氧机选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return success(aerationService.selectAerationAll());
    }

    /**
     * 查询已分配用户增氧机列表
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:list')")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectAllocatedList1(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户增氧机列表
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:list')")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList1(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:edit')")
    @Log(title = "增氧机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserAeration userAeration)
    {
        return toAjax(aerationService.deleteUserAeration(userAeration));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:edit')")
    @Log(title = "增氧机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long aerId, Long[] userIds)
    {
        return toAjax(aerationService.deleteDeptAerations(aerId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:edit')")
    @Log(title = "增氧机管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long aerId, Long[] userIds)
    {
        aerationService.checkAerationDataScope(aerId);
        return toAjax(aerationService.insertDeptAerations(aerId, userIds));
    }

    /**
     * 获取对应增氧机渔场树列表
     */
    @PreAuthorize("@ss.hasPermi('system:aeration:query')")
    @GetMapping(value = "/deptTree/{aerId}")
    public AjaxResult deptTree(@PathVariable("aerId") Long aerId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByAerId(aerId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }
}
